<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="16">
        <div class="menu">
          <el-button type="text" @click="nonDrugTableOpenAndClose" class="el-icon-circle-plus-outline" v-hasPermi="['dms:drug_model:add']">新增项目</el-button>
          <el-button type="text" @click="delDrugInDealWithDrugTable" class="el-icon-remove-outline">删除项目</el-button>
          <el-button type="text" @click="addDrugInDealWithDrug" class="el-icon-success">开立项目</el-button>
          <el-button type="text" @click="delDrugDealWith" class="el-icon-error">作废项目</el-button>
          <el-button type="text" @click="$alert('暂存')" class="el-icon-upload2">暂存</el-button>
          <el-button type="text" @click="$alert('取出暂存')" class="el-icon-download">取出暂存</el-button>
          <el-button type="text" @click="getTestList()" class="el-icon-refresh">刷新</el-button>
          <el-button round class="quick" v-if="button1Show" @click="showOutStart">快捷操作></el-button>
          <el-button round class="quick" v-if="button2Show" @click="showOutEnd">快捷操作<</el-button>
        </div>
        <!-- 添加处置项目弹窗 -->
        <el-dialog :title="title" :visible.sync="open" @row-click="choseNonDrug"   append-to-body>
          <el-row>
            <el-col :span="8" style="margin-right: 10px"><el-input  v-model="nonDrugQueryParams.name" placeholder="请输入内容"></el-input></el-col>
            <el-col :span="3"><el-button @click="getTestNonList" icon="el-icon-search" size="mini" type="cyan">搜索</el-button></el-col>
            <el-col :span="3"><el-button @click="nonDrugRest" icon="el-icon-refresh" size="mini">重置</el-button></el-col>
          </el-row>
          <el-table :data="non_drugList"   @row-click="choseNonDrug" style="max-height: 500px;overflow: auto;min-height: 500px">
            <el-table-column align="center" label="价格" prop="id" v-if="false"/>
            <el-table-column align="center" label="项目编码" prop="code"/>
            <el-table-column align="center" label="项目名称" prop="name"/>
            <el-table-column align="center" label="价格" prop="price"/>
          </el-table>
        </el-dialog>
        <!--检验执行-->
        <el-dialog  :title="title" class="app-container" :visible.sync="dealWithAddOpen"  append-to-body>
          <el-form :model="nonDealWithNonDrug" label-width="80px" size="mini">
            <el-row>
              <el-col :span="11">
                <el-form-item label="项目编码">
                  <el-input v-model="nonDealWithNonDrug.code" disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="项目名称">
                  <el-input v-model="nonDealWithNonDrug.name" disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="执行科室">
                  <el-input v-model="nonDealWithNonDrug.deptName" disabled="disabled"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="目的">
                  <el-input v-model="nonDealWithNonDrug.aim"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="要求">
                  <el-input v-model="nonDealWithNonDrug.demand"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="临床印象">
                  <el-input v-model="nonDealWithNonDrug.clinicalImpression"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="临床诊断">
                  <el-input v-model="nonDealWithNonDrug.clinicalDiagnosis"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="检查部位">
                  <el-input v-model="nonDealWithNonDrug.checkParts"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item  size="large"  class="top-right-btn">
                  <el-button type="primary" @click="CheckExecution">立即创建</el-button>
                  <el-button @click="dealWithAddOpen=false">取消</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-dialog>
        <el-tag>项目金额总计:</el-tag>
        <el-tag type="warning">{{amounts}}元</el-tag>
        <el-table border :data="testData" @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="nonDrug.code" label="项目编码"></el-table-column>
          <el-table-column prop="nonDrug.name" label="项目名称"></el-table-column>
          <el-table-column prop="nonDrug.deptName" label="执行科室"></el-table-column>
          <el-table-column prop="nonDrug.format" label="单位"></el-table-column>
          <el-table-column prop="nonDrug.price" label="单价"></el-table-column>
          <el-table-column prop="status" label="状态" >
            <template slot-scope="scope">
              <el-tag type="warning" plain size="small" >{{statusButton(scope.row.status)}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-tag type="warning" v-if="scope.row.id==null" @click="showNonDrug(scope.row)">检查执行</el-tag>
              <el-tag type="warning" v-if="scope.row.id!=null" >执行完毕</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="科室ID" prop="nonDrug.deptId" v-if="false"/>
        </el-table>
      </el-col>
      <el-col :span="8">
        <div id="quickShow" v-if="showOut">
          <el-row>
            <el-tabs v-model="firstChoice">
              <el-tab-pane label="检验模板" name="first">
                <div>
                  <el-table :data="nonDrug_testModelList" @row-click="getNonDrugModelById" @row-dblclick="getNonDrugModelDataTran">
                    <el-table-column prop="id" label="模板ID"></el-table-column>
                    <el-table-column prop="name" label="模板名"></el-table-column>
                    <el-table-column prop="aim" label="模板简介"></el-table-column>
                  </el-table>
                  <br/>
                  <div>
                    <el-row>
                      <el-tag>模版详情</el-tag>
                    </el-row>
                    <el-row>
                      <el-input v-model="non_drug_testModel_info.name" disabled="disabled">
                        <template slot="prepend" style="width: 30px">名称:</template>
                      </el-input>
                    </el-row>
                    <el-row>
                      <el-input v-model="non_drug_testModel_info.code" disabled="disabled">
                        <template slot="prepend">编码:</template>
                      </el-input>
                    </el-row>
                    <el-row>
                      <el-input v-model="non_drug_testModel_info.aim" disabled="disabled">
                        <template slot="prepend">简介:</template>
                      </el-input>
                    </el-row>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="常用检验项" name="nonTest">
                <el-table :data="usedList"  @row-click="choseNonDrug" >
                  <el-table-column label="id" v-if="false" align="center" prop="id"/>
                  <el-table-column label="项目名称" align="center" prop="name"/>
                  <el-table-column v-if="queryParams.projectType!=2" label="单价" align="center" prop="price"/>
                  <el-table-column v-if="queryParams.projectType==2" label="ICD编码" align="center" prop="icd"/>
                  <el-table-column label="项目编码" align="center" prop="code"/>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {dealWithListNon_drug_item_record,addNon_drug_item_record,save,del,getRedis,delNon_drug_item_record} from "@/api/dms/non_drug_item_record";
  import {listNon_drug_model,getNon_drug_model} from "@/api/dms/non_drug_model";
  import {listNon_drug,getNon_drug} from "@/api/dms/non_drug";
  import {listUsed} from "@/api/dms/used";
  export default {
    name: "index",
    props:['param'],
    data(){
      return {
        firstChoice: 'first',
        button1Show: true,
        button2Show: false,
        showOut: false,
        show: false,
        //查找检验操作下的数据
        testData: [],
        amounts:'',
        statusList: [],
        /**是否显示弹出层*/
        open: false,
        /**常用项查询参数*/
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          projectType: 1,
          id:null,
          name:null
        },
        /**非药品查询参数*/
        nonDrugQueryParams: {
          pageNum: null,
          pageSize: null,
          code: null,
          name: null,
          mnemonicCode: null,
          recordType: 2,
          deptId: null
        },
        /**检验执行表单参数*/
        nonDealWithNonDrug:{
          code:null,
          name:null,
          deptName:null,
          aim:null,
          demand:null,
          clinicalImpression:null,
          clinicalDiagnosis:null,
          checkParts:null,
          status:4,//检查已执行
          noDrugId:null,
          type:1,
          excuteDeptId:null,
          amount:null,
          registrationId:null,//挂号ID
        },
        /**检验执行,添加数据弹出层*/
        dealWithAddOpen:false,
        /**弹出框标题*/
        title:'',
        /**非药品数据表格(处置)*/
        non_drugList:[],
        /**选中数组*/
        ids: [],
        /**模板参数 用于查询模板*/
        models: {type: 1},
        /**模版集合*/
        nonDrug_testModelList: [],
        /**模板明细详情*/
        non_drug_testModel_info:{},
        /** 医生常用诊断（疾病）、检查检验(搁置)表格数据*/
        usedList: [],
        testReg:{
          registrationId:this.param.registrationId,
          type:1
        },
        status:2,
      }
    },
    created() {
      //常用项加载
      this.usedListLoad();
      //获取检验集合数据
      this.getTestList();
      this.getDicts("non_drug_item_record_status").then(response=>{
        this.statusList = response.data;
      });
      //非药品检验模板集合
      this.getTestModelList();

      //查询弹窗集合
      this.getTestNonList();
    },
    methods:{
      /**执行表单提交*/
      CheckExecution(){
        addNon_drug_item_record(this.nonDealWithNonDrug).then(response=>{
          if (response.code === 200) {
            this.msgSuccess("添加成功");
            this.dealWithAddOpen = false;
            //删除Redis中数据
            getNon_drug(this.nonDealWithNonDrug.noDrugId).then(response=>{
              this.del(this.param.registrationId,response.data,this.status);
            });
            this.getTestList();
            this.dealWithPrice();//金额计算
          }
        })
      },
      /**项目检验弹框*/
      showNonDrug(row){
        this.dealWithAddOpen=true;
        this.title="填写检查要求";
        this.nonDealWithNonDrug={
          code:row.nonDrug.code,
          name:row.nonDrug.name,
          deptName:row.nonDrug.deptName,
          aim:null,
          demand:null,
          clinicalImpression:null,
          clinicalDiagnosis:null,
          checkParts:null,
          status:4,//检查已执行
          noDrugId:row.nonDrug.id,
          type:1,
          excuteDeptId:row.nonDrug.deptId,
          amount:row.nonDrug.price,
          registrationId:this.param.registrationId,//挂号ID
        };
      },
      /**开立项目*/
      addDrugInDealWithDrug() {
        var that = this;//暂存This，function(){}防止函数内取不到值
        //只有id为null(数据未入数据库),并且Ids(非药品ID)对应时
        const ids = this.ids;
        const testData = this.testData;
        for (let i = 0; i < ids.length; i++) {
          for (let j = 0; j < testData.length; j++) {
            if (testData[j].id == null && ids[i] == testData[j].noDrugId) {
              //删除Redis中数据
              getNon_drug(ids[i]).then(response=>{
                this.del(this.param.registrationId,response.data,this.status);
              });
              //开立数据
              this.nonDealWithNonDrug={
                code:testData[j].nonDrug.code,
                name:testData[j].nonDrug.name,
                deptName:testData[j].nonDrug.deptName,
                aim:null,
                demand:null,
                clinicalImpression:null,
                clinicalDiagnosis:null,
                checkParts:null,
                status:4,//检查已执行
                noDrugId:testData[j].nonDrug.id,
                type:1,//未缴费
                excuteDeptId:testData[j].nonDrug.deptId,
                amount:testData[j].nonDrug.price,
                registrationId:this.param.registrationId,//挂号ID
              };
              addNon_drug_item_record(this.nonDealWithNonDrug).then(response=>{
                if (response.code === 200) {
                  setTimeout(function () {//延时操作，页面显示
                    that.msgSuccess(testData[j].nonDrug.name+"添加成功");                  },100);
                }
              }).then(async()=>{
                this.getTestList();
                this.dealWithPrice();//金额计算
              } );
            }
          }
        }
      },
      /**作废处方*/
      delDrugDealWith(){
        var that = this;//暂存This，function(){}防止函数内取不到值
        //只有id为null(数据未入数据库),并且Ids(非药品ID)对应时
        const ids = this.ids;
        const testData = this.testData;
        let drugIDs=[];
        for (let i = 0; i < ids.length; i++) {
          for (let j = 0; j < testData.length; j++) {
            if (testData[j].id != null && ids[i] == testData[j].noDrugId) {//如果：（tableData[j].id != null）是入了数据库的数据
              drugIDs.push(testData[j].id);
            }
          }
        }
        //如果有选中的符合条件的值，才删除
        if(drugIDs.length>0){
          delNon_drug_item_record(drugIDs).then(response=>{
            if(response.code==200){
              that.msgSuccess("操作成功");
            }
          }).then(async()=>{
            this.getTestList();
            this.dealWithPrice();//金额计算
          } );
        }

      },
      /**TestData数据表格查重*/
      choseTestData(id){
        let flag=true;
        this.testData.findIndex((value, index, arr) => {
          var that = this;//暂存This，function(){}防止函数内取不到值
          if(value.nonDrug.id==id){
            setTimeout(function () {//延时操作，页面显示
              that.$message.error(value.nonDrug.name+"已存在,无需重复添加！");
            },100);
            flag=false;
            return;
          }
        });
        return flag;
      },
      //双击常用项列表给检验数据表格填充数据
      getNonDrugModelDataTran(row,event,column){
        //通过模板ID添加非药品信息
        this.$confirm('是否确添加"' + row.name + '"到改患者?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).
        then(async() =>{
          //根据模板Id查询非药品信息
          getNon_drug_model(row.id).then(response =>{
            const nonDrugIdList=response.data.nonDrugIdList.split(',');
            nonDrugIdList.forEach(item=>{
              if(this.choseTestData(item)){//如果药品不重复才添加
                /*根据ID查询非药品信息*/
                getNon_drug(item).then(response => {
                  this.save(this.param.registrationId,response.data,this.status);//存入Redis中(挂号ID,药品数据,检验id2)
                  this.testData.push({
                    id:null,//处置申请明细ID
                    nonDrug:{
                      id:response.data.id,
                      code : response.data.code,
                      name : response.data.name,
                      deptName : response.data.deptName,
                      format : response.data.format,
                      price : response.data.price,
                      deptId:response.data.deptId,
                    },//药品信息
                    status:response.data.status,//状态
                    noDrugId:response.data.id//非药品ID
                  });
                  this.dealWithPrice();//金额计算
                });
              }
            })
          });
        }).then(async() =>{
          this.open=false;
        }).catch(function() {});
      },
      /**常用项数据加载*/
      usedListLoad(){
        listUsed(this.queryParams).then(response => {
          this.usedList = response.rows;
        });
      },
      /**通过模板Id查看非药品模板详情*/
      getNonDrugModelById(row, event, column){
        getNon_drug_model(row.id).then(response => {
          this.non_drug_testModel_info=response.data;
        });
      },
      //检验模板集合数据
      getTestModelList(){
        listNon_drug_model(this.models).then(response => {
          this.nonDrug_testModelList = response.rows;
        });
      },
      /**非药品列表查询参数清空*/
      nonDrugRest(){
        this.nonDrugQueryParams= {
          pageNum: null,
          pageSize: null,
          code: null,
          name: null,
          mnemonicCode: null,
          recordType: 2,
          deptId: null
        };
        this.getTestNonList();
      },
      /** 查询非药品收费项目列表(recordType==3) */
      getTestNonList() {
        listNon_drug(this.nonDrugQueryParams).then(response => {
          this.non_drugList = response.rows;
        });
      },
      /** 新增按钮操作 */
      nonDrugTableOpenAndClose() {
        this.open = true;
        this.title = "检验项目录";
      },
      /**非药品表格点击传值*/
      choseNonDrug(row, event, column){
        if(this.choseTestData(row.id)){
          this.$confirm('是否确添加"' + row.name + '"到该患者?', "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(async() =>{
            /*根据ID非药品信息*/
            getNon_drug(row.id).then(response => {
              this.save(this.param.registrationId,response.data,this.status);//存入Redis中(挂号ID,药品数据,检验Id2)
              this.testData.push({
                id:null,//处置申请明细ID
                nonDrug:{
                  id:response.data.id,
                  code : response.data.code,
                  name : response.data.name,
                  deptName : response.data.deptName,
                  format : response.data.format,
                  price : response.data.price,
                },//药品信息
                status:response.data.status,//状态
                noDrugId:response.data.id//非药品ID
              });
              this.dealWithPrice();//金额计算
            });
          }).then(async() =>{
            this.open=false;
          }).catch(function() {});
        }
      },
      /**从处置列表里删除非药品信息(与数据库无关)*/
      delDrugInDealWithDrugTable(){
        //只有id为null(数据未入数据库),并且Ids(非药品ID)对应时
        const ids=this.ids;
        const testData= this.testData;
        for(let i=0;i<ids.length;i++){
          for(let j=0;j<testData.length;j++){
            if(testData[j].id==null && ids[i]==testData[j].noDrugId){
              this.testData.splice(j,1);
              //删除Redis中数据
              getNon_drug(ids[i]).then(response=>{
                this.del(this.param.registrationId,response.data,this.status);
              });
            }
          }
        }
        /**删除完清空*/
        this.ids=[];
        /**金额结算*/
        this.dealWithPrice();
      },
      /**多选框选中数据*/
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.noDrugId);//非药品ID
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /**通过挂号ID进行Redis缓存加载*/
      getInfoByRedis(){
        getRedis(this.param.registrationId,this.status).then(response=>{
          response.data.forEach( (data,index,array)=>{
            this.testData.push({
              id:null,//处置申请明细ID
              nonDrug:data,//药品信息
              status:data.status,//状态
              noDrugId:data.id//非药品ID
            });
          })
        });
      },
      /**暂存Redis(挂号ID,药品信息)*/
      save(registrationId,data,status){
        save(data,registrationId,status);
      },

      /**删除Redis缓存*/
      del(registrationId,data,status){
        del(data,registrationId,status);
      },

      //计算金额
      dealWithPrice(){
        let price=0;
        this.testData.forEach(function(val, index, arr){
          price+=val.nonDrug.price;
        });
        this.amounts=price;
      },
      statusButton(status) {
        for(var i = 0;i < this.statusList.length;i++){
          if(this.statusList[i].dictSort==status){
            return this.statusList[i].dictLabel;
          }
        }
      },
      getTestList(){
        this.loading = true;
        let data =this.testReg;
        dealWithListNon_drug_item_record(data).then(response =>{
          this.testData = response.rows;
        }).then(async()=>{
          this.dealWithPrice();
          this.getInfoByRedis();

        });
      },
      //控制按钮显隐
      showOutEnd() {
        if (this.showOut == true) {
          this.showOut = false;
          this.button1Show = true;
          this.button2Show = false;
        }
      },
      showOutStart() {
        if (this.showOut == false) {
          this.showOut = true;
          this.button1Show = false;
          this.button2Show = true;
        }
      },
    }
  }
</script>

<style scoped>
  .iHref {
    border-radius: 10px;
    width: 95%;
    display: inline-block;
    color: cornflowerblue;
  }
  .quick{
    float: right;
    margin-right: 5%;
  }
  i{
    margin-right: 3%;
  }
</style>
